import datetime

import jwt
from django.core.cache import caches
from django.db.transaction import atomic
from django.utils import timezone
from django.utils.decorators import method_decorator
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet

from the_flash.settings import SECRET_KEY
from user.models import UserModel
from user.serializers import UserBasicSerializer, UserPostSerializer, UserUpdateSerializer
from utils.auth import CustomAuthentication
from utils.user_utils import to_md5_hex, TEL_PATTERN


@api_view(['POST'])
def login(request):
    username = request.POST.get('user_name')
    password = request.POST.get('password')
    if username and password:
        password = to_md5_hex(password)
        # password = password
        user = UserModel.objects.filter(user_name=username, password=password).first()
        if user:
            payload = {
                'exp': datetime.datetime.utcnow() + datetime.timedelta(days=1),
                'data': {'user_id': user.user_id}
            }
            token = jwt.encode(payload, SECRET_KEY, algorithm='HS256').decode()
            # with atomic():
            #     current_time = timezone.now()
            #     if not user.lastvisit or \
            #             (current_time - user.lastvisit).days >= 1:
            #         user.lastvisit = current_time
            #         user.save()

            data = {'code': 20001, 'token': token}
        else:
            data = {'code': 20002, 'hint': '用户名或密码错误'}
    else:
        data = {'code': 20003, 'hint': '请输入有效的登录信息'}
    return Response(data)


# @api_view(['GET'])
# def send_code_by_sms(request, mobile):
#     if TEL_PATTERN.fullmatch(mobile):
#         if caches['default'].get(mobile):
#             data = {'code': 10002, 'msg': '请不要在120秒以内重复发送手机验证码'}
#         else:
#             code = gen_mobile_code()
#             message = f'您的短信验证码是{code}，打死也不能告诉别人哟！【铁壳测试】'
#             send_sms_by_luosimao.delay(mobile, message=message)
#             caches['default'].set(mobile, code, timeout=120)
#             data = {'code': 10001, 'msg': '短信验证码发送成功'}
#     else:
#         data = {'code': 10003, 'msg': '请提供有效的手机号'}
#     return Response(data)


@method_decorator(decorator=atomic(), name='create')
class UserViewSet(ModelViewSet):
    queryset = UserModel.objects.all()
    serializer_class = UserBasicSerializer
    authentication_classes = (CustomAuthentication, )


    def get_serializer_class(self):
        if self.action == 'create':
            return UserPostSerializer
        elif self.action == 'update':
            return UserUpdateSerializer
        return self.serializer_class





